package com.zmn.plat.business.impl.servcategory;

import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.zmn.plat.services.interfaces.base.acceptproject.AcceptProjectService;
import com.zmn.plat.services.interfaces.base.servicecontent.ServiceContentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto.KvDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.plat.business.interfaces.servcategory.ServAssCategoryBService;
import com.zmn.plat.common.dictionary.PlatErrorCodeDict;
import com.zmn.plat.common.exception.PlatException;
import com.zmn.plat.model.entity.category.BaseCategory;
import com.zmn.plat.model.entity.servcategory.ServAssCategory;
import com.zmn.plat.model.entity.servcategory.ServAssCategoryQuery;
import com.zmn.plat.model.vo.servcategory.ServAssCategoryVO;
import com.zmn.plat.services.interfaces.servcategory.ServAssCategoryService;

/**
 * @author duanzuocai
 * @version v1.0 @类说明：
 * @modifier linfeng 前/后台服务关联产品逻辑修改 20190923
 * @since 2018/11/5 15:51
 */
@Service
public class ServAssCategoryBServiceImpl implements ServAssCategoryBService {
    private Logger logger = LoggerFactory.getLogger(ServAssCategoryBServiceImpl.class);

    @Resource
    ServAssCategoryService servAssCategoryService;

    @Override
    public List<BaseCategory> findByCategOneId(Integer servCategId, Integer categOneId) {
        ServAssCategoryQuery query = new ServAssCategoryQuery();
        query.setCategOneId(categOneId);
        query.setServCategId(servCategId);
        List<ServAssCategoryVO> list = servAssCategoryService.listByQuery(query);

        List<BaseCategory> dros = new ArrayList<>();
        for (ServAssCategoryVO vo : list) {
            BaseCategory categ = new BaseCategory();
            categ.setCategId(vo.getCategId());
            categ.setName(vo.getCategName());
            if (dros.indexOf(categ) != -1) {
                continue;
            }
            dros.add(categ);
        }

        return dros;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchAddAssociation(String creater, JSONObject object) {
        String servCategoryId = object.getString("servCategoryId");
        String showType = object.getString("showType");
        JSONArray servAssCategoryList = object.getJSONArray("servAssCategoryList");
        List<ServAssCategory> list = new ArrayList<>();
        List<ServAssCategory> insertList = new ArrayList<>();
        List<Integer> deleteIdList = new ArrayList<>();

        ServAssCategoryQuery query = new ServAssCategoryQuery();
        query.setServCategId(Integer.parseInt(servCategoryId));
        query.setShowType(Integer.parseInt(showType));
        List<ServAssCategoryVO> servAssCategoryVOS = servAssCategoryService.listByQuery(query);
        List<Integer> categIdOldList = servAssCategoryVOS.stream().map(ServAssCategoryVO::getCategId).distinct().collect(Collectors.toList());

        for (int i = 0; i < servAssCategoryList.size(); i++) {
            ServAssCategory servAssCategory = new ServAssCategory();
            ServAssCategory result = JSONObject.parseObject(servAssCategoryList.getString(i), ServAssCategory.class);
            servAssCategory.setServCategId(result.getServCategId());
            servAssCategory.setCategOneId(result.getCategOneId());
            servAssCategory.setShowType(result.getShowType());
            servAssCategory.setCategId(result.getCategId());
            servAssCategory.setCreater(creater);
            servAssCategory.setCreateTime(DateUtil.getNow());
            list.add(servAssCategory);
        }

        List<Integer> categIdNewList = list.stream().map(ServAssCategory::getCategId).distinct().collect(Collectors.toList());

        // 收集需要删除的主键ID
        deleteIdList = servAssCategoryVOS.stream().filter(servAssCategoryVO -> !categIdNewList.contains(servAssCategoryVO.getCategId())).map(ServAssCategoryVO::getGroupId).distinct()
                .collect(Collectors.toList());

        insertList = list.stream().filter(servAssCategoryVO -> !categIdOldList.contains(servAssCategoryVO.getCategId())).collect(Collectors.toList());

        try {
            if (CollectionUtil.isNotNullOrEmpty(deleteIdList)) {
                servAssCategoryService.deleteByKeys(deleteIdList);
            }

            if (CollectionUtil.isNotNullOrEmpty(insertList)) {
                servAssCategoryService.insertBatch(insertList);
            }
        } catch (org.springframework.dao.DuplicateKeyException ex) {
            logger.error("关联已经存在，不能重复添加！");
            throw new PlatException("关联已经存在，不能重复添加！");
        } catch (Exception e) {
            logger.error("操作失败！", e);
            throw new PlatException("操作失败！");
        }
    }

    @Override
    public List<KvDTO> listCategKVByServiceCategIdAndShowType(Integer serviceCategId, Integer showType) {
        if (Objects.isNull(serviceCategId) || Objects.isNull(showType)) {
            logger.error("入参不能为空serviceCategId:" + serviceCategId + ",showType:" + showType);
            throw new PlatException(PlatErrorCodeDict.ERROR_CODE_PANAM_NULL);
        }

        ServAssCategoryQuery query = new ServAssCategoryQuery();
        query.setServCategId(serviceCategId);
        query.setCategOneStatus(GlobalConsts.YES);
        query.setCategTwoStatus(GlobalConsts.YES);
        query.setShowType(showType);
        List<ServAssCategoryVO> list = servAssCategoryService.listByQuery(query);
        if (CollectionUtils.isEmpty(list)) {
            logger.info("服务分类下没有产品分类,serviceCategId:{},showType:{},errorCode:{}", serviceCategId, showType, PlatErrorCodeDict.ERROR_CODE_SERCATEGORY_DOESNOT_HAVE_CATEGORY);
            throw new PlatException(PlatErrorCodeDict.ERROR_CODE_SERCATEGORY_DOESNOT_HAVE_CATEGORY);
        }
        Map<Integer, String> categOneNameMap = list.stream().collect(Collectors.toMap(ServAssCategoryVO::getCategOneId, ServAssCategoryVO::getCategOneName, (k, v) -> k, HashMap::new));
        List<KvDTO> items = new ArrayList<>();
        KvDTO kvDTO;
        KvDTO child;
        List<KvDTO> children;
        ServAssCategoryVO servAssCategoryVO;
        for (Integer key : categOneNameMap.keySet()) {
            kvDTO = new KvDTO(key, categOneNameMap.get(key));
            children = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                servAssCategoryVO = list.get(i);
                if (Objects.equals(servAssCategoryVO.getCategOneId(), key)) {
                    child = new KvDTO(servAssCategoryVO.getCategId(), servAssCategoryVO.getCategName());
                    children.add(child);
                }
            }
            kvDTO.setChildren(children);
            items.add(kvDTO);
        }
        return items;
    }


}
